<template>
    <el-upload ref="uploadRef" action="#" :show-file-list="false" :limit="1" :on-change="handleChange" :http-request="handleUpload"
        accept=".png,.gif,.jpg,.jpeg" >
        <div class="upload-avatar-btn" :style="styles">
            <el-icon class="img-fix" color="#eee" size="20"><el-icon-edit /></el-icon>
            <el-avatar class="w-full h-full" :size="width" :src="modelValue" />
        </div>
    </el-upload>
</template>
<script lang="ts" setup>
import { ElUpload} from 'element-plus'
import { messageSuccess, messageError } from "@/utils/message";
import { uplaodImage } from "@/api/upload";
import { updateAvatar } from "@/api/user";

const props = defineProps({
    modelValue: {
        type: String,
    },
    width: {
        type: Number,
        default: 50,
    },
	accept: {
		type: String,
		required: false,
		default: '.png,.gif,.jpg,.jpeg',
	},
	size: {
		type: Number,
		required: false,
		default: 1000,
	},
});

const uploadRef = shallowRef<InstanceType<typeof ElUpload>>();

const emit = defineEmits<{
    (event: "update:modelValue", value: string): void;
    (event: "upload_confirm", value: object): void;
}>();

const styles = computed(() => {
    return {
        width: props.width + "px",
        height: props.width + "px",
        borderRadius: "50%",
    };
});

const handleChange = (file: any, fileLists: any[]) => {
    let rawFile = file.raw;
	let imgSize = rawFile.size / 1024;
	let imgType = rawFile.type;
	let acceptArr = props.accept.split('.').join('').split(',');
    if (!acceptArr.includes(imgType.substring(imgType.lastIndexOf('/') + 1, imgType.length))) {
		messageError('上传图片格式不符！');
		fileLists.splice(-1, 1);
		return false;
	}
	if (props.size && imgSize > props.size) {
		messageError('图片大小不能超过' + props.size + 'KB!');
		fileLists.splice(-1, 1);
		return false;
	}
}

const handleUpload = async(uploadFile:any) => {

    const file = uploadFile.file;
    if (!file) {
        ElMessage.error('上传文件不能为空')
        return;
    }

    try {
        const res = await uplaodImage(file);
        await updateAvatar({ avatar: res["url"] });
        messageSuccess("上传成功");
        emit("update:modelValue", res["uri"]);
        emit("upload_confirm", res);
        uploadRef.value?.clearFiles()
    } catch (e) {
        return;
    }

};
</script>

<style lang="scss" scoped>
.upload-avatar-btn {
    background-color: #fff;
    overflow: hidden;
    padding: 0;
    margin: 0;
    border-radius: 50%;
    position: relative;

    &::after {
        border: none;
    }

    &:before {
        content: "";
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.3);
        pointer-events: none;
        z-index: 1000;
    }

    .img-fix {
        position: absolute;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 1001;
    }
}
</style>
